package com.cipe.cmrs.controllers;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cipe.cmrs.model.Partner;
import com.cipe.cmrs.model.User;
import com.cipe.cmrs.service.CountryService;
import com.cipe.cmrs.service.PartnerService;
import com.cipe.cmrs.util.DateUtil;
import com.cipe.cmrs.util.NumberUtil;
import com.cipe.cmrs.util.UserUtil;

@Controller
public class PartnerController extends BaseController {

	private static final long serialVersionUID = 1815579886981166259L;
    private static final String PARAM_PREV_URL = "prevUrl";
	
	@Autowired
	private PartnerService partnerService;

	@Autowired
	private CountryService countryService;

	@RequestMapping("/secure/savePartner.do")
	public String SavePartner(@ModelAttribute("partner") Partner partner, BindingResult result, Model model, HttpServletRequest request) {
		Boolean fromProject = partner.getFromProject();
		Boolean fromProjectDetail = partner.getFromProjectDetail();
		Integer fromProjectDetailId = partner.getFromProjectDetailId();
		if (!result.hasErrors()) {
			try {
				partner = partnerService.savePartner(partner, getUserId(request));

			} catch (Exception e) {
				logger.error(getText("error.transaction"), e);
				saveError(request, getText("error.transaction"));
			}
		}
        if (null != fromProject || null != fromProjectDetail) {
            if (null != fromProject && fromProject == true) {
                return "redirect:/secure/showAddCipeprojectWithPartner.do?partnerId=" + partner.getId();
            } else if (null != fromProjectDetail && fromProjectDetail == true) {
                return "redirect:/secure/showEditCipeprojectDetailWithPartner.do?id=" + fromProjectDetailId + "&partnerId=" + partner.getId();
            } else {
                String prevUrl = request.getParameter(PARAM_PREV_URL);
                if (prevUrl.indexOf('?') != -1) {
                    prevUrl += "&partnerId=" + partner.getId();
                } else {
                    prevUrl += "?partnerId=" + partner.getId();
                }
                return "redirect:" + prevUrl;
            }
        }
		model.addAttribute("countryList", countryService.findAll());
		saveMessage(request, getText("editPartner.message.success"));
		model.addAttribute("partner", partner);
		return "editPartner";
	}

	@RequestMapping("/secure/showAddPartner.do")
	public String showAddPartner(Model model, HttpServletRequest request, @RequestParam(value="fromProject", required=false) Boolean fromProject, @RequestParam(value="fromProjectDetail", required=false) Boolean fromProjectDetail, @RequestParam(value="fromProjectDetailId", required=false) Integer fromProjectDetailId) {
        String id = request.getParameter("id");
        Partner partner = null;
        if (StringUtils.isNotBlank(id) && NumberUtil.INSTANCE.isInteger(id) && Integer.valueOf(id) > 0) {
            partner = partnerService.findById(Integer.valueOf(id));
        } else {
            partner = new Partner();
        }
		partner.setFromProject(fromProject);
		partner.setFromProjectDetail(fromProjectDetail);
		partner.setFromProjectDetailId(fromProjectDetailId);
		User user = UserUtil.INSTANCE.getCurrentUser();
		partner.setCreatedBy(user);
		partner.setCreationDate(DateUtil.getCurrentDate());
		partner.setUpdatedBy(user);
		partner.setUpdationDate(DateUtil.getCurrentDate());
		model.addAttribute("partner", partner);
		model.addAttribute("countryList", countryService.findAll());
        model.addAttribute(PARAM_PREV_URL, request.getParameter(PARAM_PREV_URL));
		return "editPartner";
	}

	@RequestMapping("/secure/showPartnerList.do")
	public String showPartnerList(Model model) {
		model.addAttribute("partners", partnerService.findAll());
		return "partnerList";
	}
}
